import express from 'express';
import {
  registerUser,
  loginUser,
  loginAdmin,
  getCurrentUser,
  getCurrentAdmin,
  changeUserPassword,
  changeAdminPassword,
  resetPassword,
  refreshToken
} from '../controllers/authController.js';
import { authenticateToken, authenticateAdmin } from '../utils/jwt.js';
import { validateRequest, userRegistrationSchema, userLoginSchema } from '../utils/validation.js';
import Joi from 'joi';

const router = express.Router();

// 用户注册验证规则
const registerValidation = validateRequest(userRegistrationSchema, 'body');

// 用户登录验证规则
const loginValidation = validateRequest(userLoginSchema, 'body');

// 管理员登录验证规则
const adminLoginSchema = Joi.object({
  username: Joi.string()
    .required()
    .messages({
      'any.required': '用户名是必填项'
    }),
  
  password: Joi.string()
    .required()
    .messages({
      'any.required': '密码是必填项'
    })
});
const adminLoginValidation = validateRequest(adminLoginSchema, 'body');

// 修改密码验证规则
const changePasswordSchema = Joi.object({
  currentPassword: Joi.string()
    .required()
    .messages({
      'any.required': '当前密码是必填项'
    }),
  
  newPassword: Joi.string()
    .min(6)
    .max(128)
    .required()
    .messages({
      'string.min': '新密码至少6个字符',
      'string.max': '新密码最多128个字符',
      'any.required': '新密码是必填项'
    })
});
const changePasswordValidation = validateRequest(changePasswordSchema, 'body');

// 重置密码验证规则
const resetPasswordSchema = Joi.object({
  email: Joi.string()
    .email()
    .required()
    .messages({
      'string.email': '請輸入有效的郵箱地址',
      'any.required': '郵箱地址是必填項'
    }),

  verification_code: Joi.string()
    .pattern(/^\d{6}$/)
    .required()
    .messages({
      'string.pattern.base': '驗證碼必須是6位數字',
      'any.required': '驗證碼是必填項'
    }),

  new_password: Joi.string()
    .min(6)
    .max(128)
    .required()
    .messages({
      'string.min': '新密碼至少6個字符',
      'string.max': '新密碼最多128個字符',
      'any.required': '新密碼是必填項'
    })
});
const resetPasswordValidation = validateRequest(resetPasswordSchema, 'body');

/**
 * @route POST /api/auth/register
 * @desc 用户注册
 * @access Public
 */
router.post('/register', registerValidation, registerUser);

/**
 * @route POST /api/auth/login
 * @desc 用户登录
 * @access Public
 */
router.post('/login', loginValidation, loginUser);

/**
 * @route POST /api/auth/reset-password
 * @desc 重置密码（忘记密码）
 * @access Public
 */
router.post('/reset-password', resetPasswordValidation, resetPassword);

/**
 * @route POST /api/auth/admin/login
 * @desc 管理员登录
 * @access Public
 */
router.post('/admin/login', adminLoginValidation, loginAdmin);

/**
 * @route GET /api/auth/me
 * @desc 获取当前用户信息
 * @access Private (User)
 */
router.get('/me', authenticateToken, getCurrentUser);

/**
 * @route GET /api/auth/admin/me
 * @desc 获取当前管理员信息
 * @access Private (Admin)
 */
router.get('/admin/me', authenticateAdmin, getCurrentAdmin);

/**
 * @route PUT /api/auth/change-password
 * @desc 修改用户密码
 * @access Private (User)
 */
router.put('/change-password', authenticateToken, changePasswordValidation, changeUserPassword);

/**
 * @route PUT /api/auth/admin/change-password
 * @desc 修改管理员密码
 * @access Private (Admin)
 */
router.put('/admin/change-password', authenticateAdmin, changePasswordValidation, changeAdminPassword);

/**
 * @route POST /api/auth/refresh
 * @desc 刷新token
 * @access Private
 */
router.post('/refresh', authenticateToken, refreshToken);

/**
 * @route POST /api/auth/admin/refresh
 * @desc 刷新管理员token
 * @access Private (Admin)
 */
router.post('/admin/refresh', authenticateAdmin, refreshToken);

/**
 * @route POST /api/auth/logout
 * @desc 用户登出（客户端处理，服务端返回成功消息）
 * @access Private
 */
router.post('/logout', authenticateToken, (req, res) => {
  res.json({
    success: true,
    message: '登出成功',
    timestamp: new Date().toISOString()
  });
});

/**
 * @route POST /api/auth/admin/logout
 * @desc 管理员登出（客户端处理，服务端返回成功消息）
 * @access Private (Admin)
 */
router.post('/admin/logout', authenticateAdmin, (req, res) => {
  res.json({
    success: true,
    message: '管理员登出成功',
    timestamp: new Date().toISOString()
  });
});

export default router;
